package com.bear.fastrepair.mvvm.ui

import android.view.View
import androidx.cardview.widget.CardView
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.NavController
import androidx.navigation.fragment.findNavController
import androidx.navigation.ui.setupWithNavController
import com.bear.fastrepair.R
import com.bear.fastrepair.base.BaseFragment
import com.bear.fastrepair.databinding.FragmentMainBinding
import com.bear.fastrepair.utils.TYPE_EMPLOYEE
import com.bear.fastrepair.utils.TYPE_MANAGER
import com.google.android.material.bottomnavigation.BottomNavigationView

class MainFragment : BaseFragment<FragmentMainBinding>() {

    private lateinit var viewModel: MainViewModel
    private lateinit var navController: NavController

    override fun init() {
        navController = findNavController()
        viewModel =
            ViewModelProvider(
                requireActivity(),
                MainViewModelFactory()
            ).get(MainViewModel::class.java)
        viewModel.loginStatus()
        if (viewModel.loginFlag) {
            navController.popBackStack()
        }
        viewModel.loginStatus.observe(viewLifecycleOwner, {
            if (viewModel.loginFlag) navController.popBackStack()
            if (!it.logged) {
                navController.popBackStack()
                navController.navigate(R.id.loginFragment)
            } else {
                viewModel.loginFlag = true
                val cardView = requireActivity().findViewById<CardView>(R.id.bottom_card_view)
                when (it.loggedType) {
                    TYPE_MANAGER -> {
                        val bottomNavigationView =
                            requireActivity().findViewById<BottomNavigationView>(R.id.bottom_navi)
                        cardView.visibility = View.VISIBLE
                        bottomNavigationView.visibility = View.VISIBLE
                        bottomNavigationView.setupWithNavController(navController)
                        navController.navigate(R.id.managerOrderFragment)
                    }
                    TYPE_EMPLOYEE -> {
                        val bottomNavigationView =
                            requireActivity().findViewById<BottomNavigationView>(R.id.bottom_navi_employee)
                        cardView.visibility = View.VISIBLE
                        bottomNavigationView.visibility = View.VISIBLE
                        bottomNavigationView.setupWithNavController(navController)
                        navController.popBackStack()
                        navController.navigate(R.id.employeeOrderFragment)
                    }
                    else -> {
                    }
                }
            }
        })
    }

    override val title: String
        get() = "首页"
}